using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Reflection;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace pop3dll
{
    public class Pop3Client
    {
        private string mServer, mUser, mPassword;
        Socket mSocket;
        System.IO.StreamReader mSocketRead;
        System.IO.StreamWriter mSocketWrite;


        public string resultLines { get { return mResultLines; } }
        public string errorMsgs { get { return errorMsg; } }

        private string mResultLine, mResultLines,errorMsg;
        private bool mConnected = false;

        public Pop3Client(string user, string server, string pass)
        {
            mUser = user;
            mServer = server;
            mPassword = pass;
        }

        public bool connect()
        {
            bool result = false;
            int port = 110;
            mSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            mSocket.Connect(mServer, port);

            mSocketRead = new System.IO.StreamReader(new NetworkStream(mSocket));
            mSocketWrite = new System.IO.StreamWriter(new NetworkStream(mSocket));

            mResultLine = mSocketRead.ReadLine();
            mResultLines += mResultLine + "\r\n";

            if (!mResultLine.StartsWith("+"))
            {
                errorMsg = mResultLines;
                goto end3;
            }
            mSocketWrite.WriteLine("USER " + mUser);
            mSocketWrite.Flush();
            mResultLine = mSocketRead.ReadLine();
            mResultLines += mResultLine + "\r\n";

            if (!mResultLine.StartsWith("+"))
            {
                errorMsg = mResultLines;
                goto end3;
            }
            mSocketWrite.WriteLine("PASS " + mPassword);
            mSocketWrite.Flush();
            mResultLine = mSocketRead.ReadLine();
            mResultLines += mResultLine + "\r\n";

            if (!mResultLine.StartsWith("+"))
            {
                errorMsg = mResultLines + "\r\n";
                goto end3;
            }
            mConnected = true;

            return true;

        end3:
            mSocketRead.Close();
            mSocketWrite.Close();
            mSocket.Close();

            return result;
        }

        public void disconnect()
        {
            try
            {
                if (mConnected)
                {
                    mSocketWrite.Write("quit\r\n");
                    mSocketWrite.Flush();
                    mResultLines = mSocketRead.ReadLine();
                    
                    mSocketRead.Close();
                    mSocketWrite.Close();
                    mSocket.Close();
                    mResultLines = " Disconnected \r\n";
                    mConnected = false;
                }
            }catch(Exception e)
            {
            
                errorMsg = e.Message;
            }



        }
        public int getCount()
        { 
            int c = 0 ;
            mResultLines = "";
            try
            {
                mSocketWrite.WriteLine("list");
                mSocketWrite.Flush();
                mResultLine = mSocketRead.ReadLine();
                mResultLines += mResultLine + "\r\n";
                while (!mResultLine.StartsWith("."))
                {
                    c++;
                    mResultLine = mSocketRead.ReadLine();
                    mResultLines += mResultLine + "\r\n";
                }
                if (mResultLine.StartsWith("."))
                    c--;
            }
            catch (Exception batbeer) {
                errorMsg = "exception in getCount() " + batbeer.Message + "\r\n";
                c = -1;            

            }
            return c;
        }
        public string getMessage(int num)
        { /* code to get message here */
            if (!File.Exists(@"email.txt"))
            {
                string msg = "";
                string msgFull = "";
                mSocketWrite.WriteLine("retr " + num);
                mSocketWrite.Flush();

                msg = mSocketRead.ReadLine();
                msgFull += msg + "\r\n";
                if (!msgFull.StartsWith("-ERR"))
                {
                    while (!msg.StartsWith("."))
                    {
                        msg = mSocketRead.ReadLine();
                        msgFull += msg + "\r\n";
                    }
                }
                else
                {
                    msgFull = msgFull.Substring(msgFull.IndexOf(" "));
                }
                return msgFull;
            }
            else
            {
                FileStream fStream = new FileStream(@"email.txt", FileMode.Open);
                StreamReader sReader = new StreamReader(fStream);
                //sReader.ReadToEnd();
                //MessageBox.Show(sReader.ReadToEnd());
                string storage = sReader.ReadToEnd();
                sReader.Close();
                fStream.Close();
                string[] delim = new string[] {"\r\nEOE:\r\n"};
                string[] mail = storage.Split(delim,StringSplitOptions.RemoveEmptyEntries);

                return mail[num-1];

            }
        }
        public string storeMessage(int num)
        { /* code to get message here */
           
                string msg = "";
                string msgFull = "";
                mSocketWrite.WriteLine("retr " + num);
                mSocketWrite.Flush();

                msg = mSocketRead.ReadLine();
                msgFull += msg + "\r\n";
                if (!msgFull.StartsWith("-ERR"))
                {
                    
                    
                    while (!msg.Equals("."))
                    {
                        msg = mSocketRead.ReadLine();
                        msgFull += msg + "\r\n";
                    }
                }
                else
                {
                    msgFull = msgFull.Substring(msgFull.IndexOf(" "));
                }
                return msgFull;
           
        }
        public string getMessageTop(int num)
        { /* code to get message top here */
            string msg = "";
            string msgTop = "";
            mSocketWrite.WriteLine("top " + num + " 1");
            mSocketWrite.Flush();
            msg = mSocketRead.ReadLine();
            msgTop += msg + "\r\n";

            while (!msg.StartsWith("."))
            {
                msg = mSocketRead.ReadLine();
                msgTop += msg + "\r\n";
            }
            return msgTop;
        }

        public class MessageHeader
        {
            public string subject;
            public string from;
            public string date;
            public string size;

        }
        
        public MessageHeader getMessageHeader(int num)
        {
            MessageHeader current = new MessageHeader();

            if (!File.Exists(@"email.txt"))
            {
                System.IO.StreamReader headerReader = new StreamReader(new NetworkStream(mSocket));
                System.IO.StreamWriter headerWrite = new StreamWriter(new NetworkStream(mSocket));
                headerWrite.WriteLine("top " + num + " 0");
                headerWrite.Flush();
                string msg;
                //string msgFull= new String(' ');

                msg = headerReader.ReadLine();
                //msgFull += msg + "\r\n";
                if (!msg.StartsWith("-ERR"))
                {
                    while (!msg.StartsWith("."))
                    {
                        if (msg.ToUpper().StartsWith("SUBJECT:"))
                        {
                            current.subject = msg.Substring(msg.IndexOf(':') + 1);
                        }
                        else if (msg.ToUpper().StartsWith("DATE:"))
                        {
                            current.date = msg.Substring(msg.IndexOf(':') + 1);
                        }
                        else if (msg.ToUpper().StartsWith("FROM:"))
                        {
                            current.from = msg.Substring(msg.IndexOf(':') + 1);
                        }


                        msg = headerReader.ReadLine();
                    }
                }

                
            }
            else
            {
                FileStream fStream = new FileStream(@"email.txt", FileMode.Open);
                StreamReader sReader = new StreamReader(fStream);
                string storage = sReader.ReadToEnd();
                string[] delim = new string[] { "\r\nEOE:\r\n" };
                string[] mail = storage.Split(delim, StringSplitOptions.RemoveEmptyEntries);
                sReader.Close();
                fStream.Close();
                string[] delim2 = new string[] { "\r\n\r\n" };
                string[] header = mail[num - 1].Split(delim2,StringSplitOptions.RemoveEmptyEntries);

                //sReader.ReadToEnd();
                //MessageBox.Show(sReader.ReadToEnd());
                StringReader headerReader = new StringReader( header[0] + "\r\n.\r\n" );
                string headerLine = headerReader.ReadLine();
                
                
                while (headerLine != null)
                {
                    //MessageBox.Show(headerLine);
                    if (headerLine.ToUpper().StartsWith("SUBJECT:"))
                    {
                        current.subject = headerLine.Substring(headerLine.IndexOf(':') + 1);
                    }
                    else if (headerLine.ToUpper().StartsWith("DATE:"))
                    {
                        current.date = headerLine.Substring(headerLine.IndexOf(':') + 1);
                    }
                    else if (headerLine.ToUpper().StartsWith("FROM:"))
                    {
                        current.from = headerLine.Substring(headerLine.IndexOf(':') + 1);
                    }
                    headerLine = headerReader.ReadLine();
                }

                

            }
            return current;
        }

        public bool deleteMessage(int num)
        {
            System.IO.StreamReader delReader = new StreamReader(new NetworkStream(mSocket));
            System.IO.StreamWriter delWrite = new StreamWriter(new NetworkStream(mSocket));

            //msgFull += msg + "\r\n";
            DialogResult pleaseDont =  MessageBox.Show("Would you like to Delete this Message?",
                        "FOLLOW THE MOUNTAINS!",
                        MessageBoxButtons.OKCancel);
            if (pleaseDont.Equals(DialogResult.OK))
            {
                delWrite.WriteLine("dele " + num);
                delWrite.Flush();
                string msg = delReader.ReadLine();
                if (!msg.StartsWith("-ERR"))
                {
                    MessageBox.Show("AllyouremailRBelongToserver!");
                }
                else
                {
                    MessageBox.Show(msg);

                }
            }

            return true;
        }

    } 
}
